{% extends 'base.combined.class' %}

{% block content %}
class {{ class_name }} {

    private static function findMax($nums) {
        $i = 0; $l = count($nums); $idx = 0;
        for (; $i < $l; $i++) {
            $idx = $nums[$i] > $nums[$idx] ? $i : $idx;
        }
        return $idx;
    }

    private static function normVals($nums) {
        $i = 0; $l = count($nums);
        $result = [];
        $sum = 0.;

        for ($i = 0; $i < $l; $i++) {
            $sum += $nums[$i];
        }
        if($sum === 0) {
            for ($i = 0; $i < $l; $i++) {
                $result[$i] = 1. / $l;
            }
        } else {
            for ($i = 0; $i < $l; $i++) {
                $result[$i] = $nums[$i] / $sum;
            }
        }
        return $result;
    }

    private static function compute($features) {
        if (sizeof($features) != {{ n_features }}) { return -1; }
        $classes = array_fill(0, {{ n_classes }}, 0);
        {{ tree | indent(4, True) }}
        return $classes;
    }

    public static function predict($features) {
        $classes = {{ class_name }}::compute($features);
        return {{ class_name }}::findMax($classes);
    }

    public static function predictProba($features) {
        $classes = {{ class_name }}::compute($features);
        return {{ class_name }}::normVals($classes);
    }

}

if ($argc > 1) {

    // Features:
    array_shift($argv);
    $features = $argv;

    {% if is_test or to_json %}
    // Get JSON:
    $prediction = {{ class_name }}::predict($argv);
    $probabilities = {{ class_name }}::predictProba($features);
    fwrite(STDOUT, json_encode(array("predict" => $prediction, "predict_proba" => $probabilities)));
    {% else %}
    // Get class prediction:
    $prediction = {{ class_name }}::predict($argv);
    fwrite(STDOUT, "Predicted class: #" . strval($prediction) . "\n");

    // Get class probabilities:
    $probabilities = {{ class_name }}::predictProba($features);
    for ($i = 0; $i < count($probabilities); $i++) {
        fwrite(STDOUT, "Probability of class #" . strval($i) . " = " . strval($probabilities[$i]) . "\n");
    }
    {% endif %}

}
{% endblock %}